using System.Data.Linq.Mapping;
using System.Linq;

namespace TruyenTranhCrawler.Data
{
    [Table]
    public class BookByAuthor : BaseObject
    {
        #region Properties
        [Column(IsPrimaryKey = true)]
        public int AuthorId { get; set; }
        [Column]
        public string BookIds { get; set; }
        #endregion

        public static void AddBook(int authorId, int bookId)
        {
            using (var context = new CmsDataContext())
            {
                var bookids = context.BookByAuthors.Where(x => x.AuthorId == authorId).Select(x => x.BookIds).FirstOrDefault();
                if (bookids != null)
                {
                    var full = "," + bookids + ",";
                    if (full.IndexOf("," + bookId + ",") < 0)
                    {
                        bookids += "," + bookId;
                        context.ExecuteCommand("update BookByAuthor set BookIds={0} where AuthorId={1}", bookids, authorId);
                    }
                }
                else
                {
                    context.ExecuteCommand("INSERT BookByAuthor(AuthorId,BookIds) values({0},{1})", authorId, bookId);
                }
            }
        }
    }
}
